<?php

$thisPage = "subscribe";
$subpage = getRequestParameter("subpage", false);

TemplateHelper::useLayout("form");

Log::info("Loading page functions: $thisPage");

addDataService("dosubscribe");
addDataService("userexists");
addDataService("ack");
addDataService("unsubscribe");
addhtmlSErvice("unsubscribe");

function executeService($serviceName, $params) {
    switch ($serviceName) {
        case "userexists" : { return service_userexists($params); }
        case "dosubscribe" : { return service_dosubscribe($params); }
        case "ack" : { return service_ack($params); }
        case "unsubscribe" : { return service_unsubscribe($params); }
    }
}

function buildLayout(&$smarty) {
    global $subpage;

    Log::debug("Executing function: buildLayout");
    if ($subpage === false) {
        $smarty->assign("form", getsubscribeFormData($smarty));
    } else if ($subpage == "success") {
        $smarty->assign("form", getSuccessContent($smarty));
    } else if ($subpage == "ackfail") {
        $smarty->assign("form", getAckFailContent($smarty));
    } else if ($subpage == "acknowledged") {
        $smarty->assign("form", getAckSuccessContent($smarty));
    } else if ($subpage == "unsubscribe_success") {
        $smarty->assign("form", getUnsubscribeSuccessContent($smarty));
    }
}

function service_userexists($params) {
    Log::info("executing service: userexists");
    $exists = false;
    $success = true;
    $r = "";
    try {
        Database::loadModel("user");
        $exists = Database::getModel()->userExists($params['username']);
    }
    catch (Exception $e) {
        $success = false;
        $errorMsg = $e->getMessage();
    }
    $result = array(
        exists => $exists,
    );
    Log::info("Finishing service: userexists");
    if ($success) {
        $r = serviceSuccessful($result);
    } else {
        $r = serviceFailure($result, $e->getMessage());
    }
    return $r;
}

function service_unsubscribe($params) {
    global $smarty;
    $usemail = getConfigParameter("site", "newsletter_unsubscribe_email");
    $adminservice = getConfigParameter("site", "adminService");
    $email = getRequestParameter("email");
    Log::debug("email address=" . $email);
    $sign = $adminservice['emailSign'];
    $content =
<<<EMAIL
Dear administrator,
<p>
one of your registered users has been requested an unsubscription from our newsletter.<br>
Details:<br>
Email address: $email
<p>

Regards,<br>
$sign
EMAIL;
    sendEmailWithContent($usemail, "Newsletter unsubscription", $content);
/*
    $group = getRequestParameter("group");
    $email = getRequestParameter("email");
    if ($group == "7") {
        Database::loadModel("groupmembers");
    } else if ($group == "8") {
        Database::loadModel("groupmembers");
    } else if ($group == "9") {
        Database::loadModel("groupmembers");
    } else {
        Database::loadModel("user");
    }
    Database::getModel()->unsubscribeEmail($email);
*/
    return redirect("subscribe", "unsubscribe_success");
}

function service_dosubscribe($params) {
    global $thisPage;

    Log::info("executing service: dosubscribe");
    $success = true;
    $result = "";
    $errorMsg = "";
    $success = true;
    $captcha = getCaptchaObject();
    if (!$captcha->validate($params['random'])) {
        $errorMsg = "Captcha session key does not exist.";
        $success = false;
    } else if (!$captcha->verify($params['captcha'])) {
        $errorMsg = "You have entered a wrong captcha code.";
        $success = false;
    } else {
        try {
            Database::loadModel("subscriptions");
            $userdata = sophisticateData($params);
            $userdata['ticket'] = substr(md5(rand() % 10000), 0, 6);
            Database::addNew($userdata);
            $params['link'] = buildServiceURL($thisPage, "ack", array(
                ticket => $userdata['ticket']
            ));
            sendEmail("subscribe", $userdata['email'], $params);
        }
        catch (Exception $e) {
            $success = false;
            $errorMsg = $e->getMessage();
        }
    }
    if ($success) {
        Log::info("Finished service: dosubscribe status: success");
        $result = serviceSuccessfulWithRedirect(array(), "subscribe", "success");
    } else {
        Log::info("Finished service: dosubscribe status: failure");
        $result = serviceFailure(array(), $errorMsg);
    }
    return $result;
}

function service_ack($params) {
    Log::info("executing service: ack");
    $success = true;
//print_r($params);
    try {
        Database::loadModel("subscriptions");
        $success = Database::getModel()->evaluate($params['ticket']);
    }
    catch (Exception $e) {
        $success = false;
    }
    if ($success) {
        Log::info("Finished service: ack status: success");
        $result = redirect("subscribe", "acknowledged");
    } else {
        Log::info("Finished service: ack status: failure");
        $result = redirect("subscribe", "ackfail");
    }
    return $result;
}

function getPageHeader() {
    Log::debug("Executing function: getPageHeader");
    return TemplateHelper::getDefaultPageHeader();
}

function getPageFooter() {
    Log::debug("Executing function: getPageFooter");
    return TemplateHelper::getDefaultPageFooter();
}

function getsubscribeFormData(&$smarty) {
    global $thisPage;
    Log::debug("Executing function: getsubscribeFormData");
    $smarty->assign("captcha", TemplateHelper::addCaptchaService());
    return array(
        title => "Subscription",
        content => $smarty->fetch(TemplateHelper::getTemplateFile($thisPage, "subscribe_content")),
        style => "largeform",
    );
}

function getSuccessContent(&$smarty) {
    global $thisPage;
    Log::debug("Executing function: getSuccessContent");
    return array(
        title => "subscribe to impex",
        content => $smarty->fetch(TemplateHelper::getTemplateFile($thisPage, "subscribe_success")),
    );
}

function getAckFailContent(&$smarty) {
    global $thisPage;
    Log::debug("Executing function: getAckFailContent");
    return array(
        title => "Acknowledge failed",
        content => $smarty->fetch(TemplateHelper::getTemplateFile($thisPage, "subscribe_ackfail")),
    );
}

function getAckSuccessContent(&$smarty) {
    global $thisPage;
    Log::debug("Executing function: getAckSuccessContent");
    return array(
        title => "Acknowledge successful",
        content => $smarty->fetch(TemplateHelper::getTemplateFile($thisPage, "subscribe_acksuccess")),
    );
}

function getUnsubscribeSuccessContent(&$smarty) {
    global $thisPage;
    Log::debug("Executing function: getAckSuccessContent");
    return array(
        title => "Unsubscription successful",
        content => $smarty->fetch(TemplateHelper::getTemplateFile($thisPage, "unsubscribe_success")),
    );
}

?>
